package org.biouno.unochoice;

import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import hudson.model.AbstractItem;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import jenkins.model.Jenkins;
import org.jenkinsci.plugins.database.Database;
import org.jenkinsci.plugins.database.GlobalDatabaseConfiguration;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest2;

public class MySQLDatabaseUtils {

    public static List<UserRemoteConfig> userRemoteConfigsNew() {
        List<UserRemoteConfig> list = new ArrayList<UserRemoteConfig>();
//        list.add(new UserRemoteConfig("https://github.com/biouno/uno-choice.git",
//                "origin", "master", "gitlab-ci-token",
//                "origin", "gitlab-ci-token", "master"));
        return list;
    }

    public static String detectProject() {
        try {
            final StaplerRequest2 currentRequest = Stapler.getCurrentRequest2();
            if (currentRequest != null) {
                final Ancestor ancestor =
                        currentRequest.findAncestor(AbstractItem.class);
                if (ancestor != null) {
                    final Object o = ancestor.getObject();
                    if (o instanceof AbstractItem) {
                        System.err.println("detectProject");
                        return ((AbstractItem) o).getFullName();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println("detectProject-error");
        return null;
    }

    public static List<HashMap<String, Object>> executeQuery(String sql) {
        List<HashMap<String, Object>> list = new ArrayList<>();
        Connection connection = null;
        try {
            System.err.println("executeQuery");
            if (GlobalDatabaseConfiguration.get() == null)
                return list;
            Database database = GlobalDatabaseConfiguration.get().getDatabase();
            if (database.getDescriptor() != null &&
                    database.getDescriptor().getDisplayName().equals("MySQL")) {
                connection = database.getDataSource().getConnection();
                if (!connection.isClosed()) {
                    PreparedStatement prepareStatement = connection.prepareStatement(sql);
                    ResultSet resultSet = prepareStatement.executeQuery();
                    while (resultSet.next()) {
                        ResultSetMetaData metaData = resultSet.getMetaData();
                        HashMap<String, Object> map = new HashMap<>();
                        for (int i = 1; i <= metaData.getColumnCount(); i++) {
                            map.put(metaData.getColumnName(i), resultSet.getObject(i));
                        }
                        list.add(map);
                    }
                    //                    System.err.println("executeQuery  size " +
                    //                    list.size());
                    connection.close();
                    return list;
                } else {
                    //                    System.err.println("sql error: connection is
                    //                    closed");
                }
            } else {
                //                System.err.println("sql error: database is not
                //                MySQL");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            //            System.err.println("sql error:" + e.getMessage());
            e.printStackTrace();
        }
        try {
            if (connection != null && !connection.isClosed()) connection.close();
        }catch (Exception e){

        }

        return list;
    }

    public static boolean createProjectInfo() {
        String sql = "create table project_info\n"
                + "(\n"
                + "    id             varchar(32) not null\n"
                + "        primary key comment '项目id',\n"
                + "    create_time    datetime    null comment '创建时间',\n"
                + "    modify_time    datetime    null comment '修改时间',\n"
                + "    project_name   varchar(255) comment '项目名称',\n"
                + "    job_id         varchar(32) comment '作业id',\n"
                + "    credentials_id varchar(32) comment '认证id',\n"
                + "    git_url        varchar(32) comment 'git地址',\n"
                + "    groovy_Script text comment 'groovy脚本',\n"
                + "    param text comment '参数'\n"
                + ");";
        return executeSql(sql);
    }


    public static boolean updateProjectInfo(String project_name, String param) {

        List<HashMap<String, Object>> list = executeQuery("select * from project_info where project_name=\"" + project_name + "\";");
        List<Object> params = new ArrayList<>();
        if (list.size() > 0) {
            params.add(param);
            params.add(project_name);
            boolean res = executeSql("update project_info set param=? where project_name=?", params);
            System.out.println("updateProjectInfo res: " + (res ? "success" : "fail"));
            return res;
        }
        createProjectInfo();
        executeSql("delete from project_info where project_name=\"" + project_name + "\";");
        params.add(project_name);
        params.add(project_name);
        params.add(param);
        boolean res = executeSql("insert into project_info(id,project_name,param) values (?,?,?)", params);
        System.out.println("createProjectInfo res: " + (res ? "success" : "fail"));
        return res;
//        return  true;
    }

    public static boolean executeSql(String sql) {
        Connection connection = null;
        try {
            System.err.println("executeSql:" + sql);
            if (GlobalDatabaseConfiguration.get() == null)
                return false;
            Database database = GlobalDatabaseConfiguration.get().getDatabase();
            if (database.getDescriptor().getDisplayName().equals("MySQL")) {
                connection = database.getDataSource().getConnection();
                if (!connection.isClosed()) {
                    PreparedStatement prepareStatement = connection.prepareStatement(sql);
                    boolean res = prepareStatement.execute();
                    connection.close();
                    return res;
                } else {
                    System.err.println("sql error: connection is closed");
                }
            } else {
                System.err.println("sql error: database is not MySQL");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            //            System.err.println("sql error:" + e.getMessage());
            e.printStackTrace();
        }
        try {
            if (connection != null && !connection.isClosed()) connection.close();
        }catch (Exception e){

        }
        return false;
    }

    public static boolean executeSql(String sql, List<Object> params) {
        Connection connection =null;
        try {
            System.err.println("executeSql:" + sql);
            if (GlobalDatabaseConfiguration.get() == null)
                return false;
            Database database = GlobalDatabaseConfiguration.get().getDatabase();
            if (database.getDescriptor().getDisplayName().equals("MySQL")) {
                 connection = database.getDataSource().getConnection();
                if (!connection.isClosed()) {
                    PreparedStatement prepareStatement = connection.prepareStatement(sql);
                    for (int i = 0; i < params.size(); i++) {
                        if (params.get(i) instanceof Integer) {
                            prepareStatement.setInt(i + 1, (Integer) params.get(i));
                        } else if (params.get(i) instanceof Long) {
                            prepareStatement.setLong(i + 1, (Long) params.get(i));
                        } else if (params.get(i) instanceof Boolean) {
                            prepareStatement.setBoolean(i + 1, (Boolean) params.get(i));
                        } else if (params.get(i) instanceof Double) {
                            prepareStatement.setDouble(i + 1, (Double) params.get(i));
                        } else if (params.get(i) instanceof Float) {
                            prepareStatement.setFloat(i + 1, (Float) params.get(i));
                        } else {
                            prepareStatement.setString(i + 1, params.get(i).toString());
                        }

                    }
                    boolean res = prepareStatement.execute();
                    connection.close();
                    return res;
                } else {
                    System.err.println("sql error: connection is closed");
                }
            } else {
                System.err.println("sql error: database is not MySQL");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            //            System.err.println("sql error:" + e.getMessage());
            e.printStackTrace();
        }
        try {
            if (connection != null && !connection.isClosed()) connection.close();
        }catch (Exception e){

        }
        return false;
    }

    public static HashMap executeQueryProjectInit() {
        Jenkins jenkins = Jenkins.get();
        String j = jenkins.getFullName();
        HashMap hashMap = new HashMap<>();
        List<HashMap<String, Object>> list = new ArrayList<>();
        List<HashMap<String, Object>> package_info =
                executeQuery("select * from package_info where id='" + j + "'");
        if (package_info != null && package_info.size() > 0) {
        }
        hashMap.put("package", list);
        return hashMap;
    }
}
